<?php
/*
 * program:	均源
 * author:	雨中漫步 & 上善若水 & qhxin
 * email:	qhxin@qhxin.com
 * date:	2014/11/11
 * description:	又是一年双十一，不能剁手，就写点东西吧~~~~~~
 */

defined('IN_SCHOOL') or die();

/*{TranslateTagBegin}*/
class model_kv extends base_model{

	//hook mod_kv_start.php
	private $table;

	function __construct() {
		//hook mod_kv_init_init_before.php
		parent::__construct();
		$this->table = 'kv';
		//hook mod_kv_init_init_end.php
	}
	
	//带有过期时间的get
	public function get($key) {
		//hook mod_kv_get.php
		$key = str_replace('-','',$key);
		$arr = $this->db->get($this->table."-k-$key");
		return !empty($arr) && (empty($arr['expiry']) || $arr['expiry'] > $_SERVER['time']) ? core::json_decode($arr['v']) : FALSE;
	}
	
	//带有过期时间的set
	public function set($key, $value, $life = 0) {
		//hook mod_kv_set.php
		$key = str_replace('-','',$key);
		$value = core::json_encode($value);
		$arr = array();
		$arr['k'] = $key;
		$arr['v'] = $value;
		$arr['expiry'] = $life ? $_SERVER['time'] + $life : 0;
		return $this->db->set($this->table."-k-$key", $arr);
	}
	
	//删除
	public function delete($key) {
		//hook mod_kv_delete.php
		$key = str_replace('-','',$key);
		return $this->db->delete($this->table."-k-$key");
	}
	
	//过期删除
	public function del_old_ten_kv_after_one_mouth() {
		//hook mod_kv_del_old_ten_kv_after_one_mouth.php
		$ltim = $_SERVER['time'] - 2592000;
		$cond = array('expiry' => array('>'=>0,'<'=>$ltim) );
		$arr = $this->db->index_fetch_id($this->table , 'k',
							$cond, array(), 0, 10);
		foreach($arr as $k=>$v) {
			$this->db->delete($v);
		}
	}
	
	
	//hook mod_kv_end.php
}
/*{TranslateTagEnd}*/

?>